package idx

import (
	"bytes"
	"encoding/binary"
	"time"
)

const FixedLength = 44   //除了name的固定长度
const isDel uint32 = 0x1 //删除

/*
	idxHead offset size expire md5 name
	   4	  8		8	  8	    16	max:255
*/

type Idx struct {
	Name   []byte
	Md5    []byte
	Expire int64
	Size   int64
	Offset int64
	IdxHead
}

func NewIdx(name string, size int64) *Idx {
	//name最多支持255 的长度
	_n := []byte(name)
	if len(_n) > 255 {
		_n = _n[:255]
	}
	//head
	head := IdxHead(0)
	head.SetLen(uint32(len(_n)))

	idx := &Idx{
		Name:    _n,
		Size:    size,
		IdxHead: head,
	}
	return idx
}

func (f *Idx) SetMd5(md5 []byte) {
	f.Md5 = md5[:16] //保证md是16个字节
}

func (f *Idx) SetOffset(n int64) {
	f.Offset = n
}

func (f *Idx) SetExpire(expire time.Time) {
	t := int64(0)
	if !expire.IsZero() {
		t = expire.Unix()
	}
	f.Expire = t
}

func (f *Idx) IdxOffset() int64 {
	return f.Offset - f.Count()
}

func (f *Idx) Expired() bool {
	if f.Expire != 0 && f.Expire <= time.Now().Unix() {
		return true
	}
	return false
}

func (f *Idx) Bytes() []byte {
	b := bytes.Buffer{}
	_ = binary.Write(&b, binary.BigEndian, f.IdxHead)
	_ = binary.Write(&b, binary.BigEndian, f.Offset)
	_ = binary.Write(&b, binary.BigEndian, f.Size)
	_ = binary.Write(&b, binary.BigEndian, f.Expire)
	b.Write(f.Md5)
	b.Write(f.Name)
	return b.Bytes()
}

func FromBytes(b []byte) *Idx {
	fi := Idx{}
	fi.IdxHead = IdxHead(binary.BigEndian.Uint32(b[0:4]))
	fi.Offset = int64(binary.BigEndian.Uint64(b[4:12]))
	fi.Size = int64(binary.BigEndian.Uint64(b[12:20]))
	fi.Expire = int64(binary.BigEndian.Uint64(b[20:28]))
	fi.Md5 = b[28:44]
	fi.Name = b[44:]
	return &fi
}
